package com.atguigu.gmall.wms.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

import javax.annotation.PostConstruct;

@Configuration
@Slf4j
public class RabbitmqConfig {
    @Autowired
    RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback((@Nullable CorrelationData correlationData, boolean ack, @Nullable String cause)->{
            if (!ack){
                log.error("发送交换机的消息失败，原因是：{}，元数据是：{}",cause,new String(correlationData.getReturnedMessage().getBody()));
            }
            rabbitTemplate.setReturnCallback((Message message, int replyCode, String replyText, String exchange, String routingKey)->{
                log.error("发送到队列的消息失败，消息是：{}，返回code是{}，回复的text是{}，交换机是{}，路由键是{}",message,replyCode,replyText,exchange,routingKey);
            });
        });
    }
    /**
     * 延时队列 stock_ttl_queue
     */
    @Bean
    public Queue queue(){
        return QueueBuilder.durable("STOCK_TTL_QUEUE").ttl(100000)
                .deadLetterExchange("ORDER_CREATE_EXCHANGE").deadLetterRoutingKey("stock.unlock").build();
    }

    /**
     * 把延时队列绑定到延时交换机：stock.ttl
     */
    @Bean
    public Binding binding(){
        return new Binding("STOCK_TTL_QUEUE", Binding.DestinationType.QUEUE,
                "ORDER_CREATE_EXCHANGE", "stock.ttl", null);
    }


}
